﻿using Autofac;
using AutoMapper;
using Gufa.WebAPI.AutoMapper;
using System.Reflection;

namespace Gufa.Web.AutofacDI
{
    public class AutofacModuleRegister : Autofac.Module
    {
        // 重写Autoface中的Load方法，从而实现注入的操作
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);
            var AppServices = Assembly.Load("Gufa.Services");
            var IAppServices = Assembly.Load("Gufa.IServices");
            var AppRepository = Assembly.Load("Gufa.Repositories");
            var IAppRepository = Assembly.Load("Gufa.IRepositories");
            // 这里做了一个约定，服务层中的类都是以Service结尾，仓储项目中的类都是以Repository结尾
            builder.RegisterAssemblyTypes(IAppServices, AppServices).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();//是以接口方式进行注入,

            builder.RegisterAssemblyTypes(IAppRepository, AppRepository).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces();

            // Register AutoMapper profiles
            builder.Register(context => new MapperConfiguration(cfg =>
            {
                // Register all profiles in the current assembly
                cfg.AddMaps(typeof(AutoMapperProfiles).GetTypeInfo().Assembly);
            })).AsSelf().SingleInstance();

            // Register IMapper
            builder.Register(context =>
            {
                var config = context.Resolve<MapperConfiguration>();
                return config.CreateMapper(context.Resolve);
            }).As<IMapper>().InstancePerLifetimeScope();
        }
    }
}
